<template>
  <Form
    :label-width="80"
    ref="formValidate"
    :rules="ruleValidate"
    :model="formValidate"
    label-position="left"
  >
    <FormItem label="用户账号" prop="userAccount">
      <i-input type="text" v-model="formValidate.userAccount" placeholder="账号/身份证号" v-show="type !== 3">
      </i-input>
      <span v-show="type === 3">{{formValidate.userAccount}}</span>
    </FormItem>
    <FormItem label="用户密码" prop="userPassword" v-if="type==1">
      <i-input type="text" v-model="formValidate.userPassword" placeholder="默认系统配置密码">
      </i-input>
    </FormItem>
    <FormItem prop="userName" label="用户姓名">
      <i-input type="text" v-model="formValidate.userName" placeholder="用户姓名" v-show="type !== 3">
      </i-input>
      <span v-show="type === 3">{{formValidate.userName}}</span>
    </FormItem>
    <FormItem label="工号" prop="workNumber">
      <i-input type="number" v-model="formValidate.workNumber" placeholder="工号" v-show="type !== 3"></i-input>
      <span v-show="type === 3">{{formValidate.workNumber}}</span>
  </FormItem>
    <FormItem label="邮箱" prop="email">
      <i-input type="text" v-model="formValidate.email" placeholder="邮箱" v-show="type !== 3"></i-input>
      <span v-show="type === 3">{{formValidate.email}}</span>
    </FormItem>
    <FormItem label="手机号码" prop="phone">
      <i-input type="text" v-model="formValidate.phone" placeholder="手机号码" v-show="type !== 3">
      </i-input>
      <span v-show="type === 3">{{formValidate.phone}}</span>
    </FormItem>
    <FormItem label="身份证号" prop="idCard">
      <i-input type="text" v-model="formValidate.idCard" placeholder="身份证号" v-show="type !== 3">
      </i-input>
       <span v-show="type === 3">{{formValidate.idCard}}</span>
    </FormItem>
    <FormItem label="性别" prop="sex">
      <RadioGroup v-model="formValidate.sex">
        <Radio :label='0' :disabled="type === 3">默认</Radio>
        <Radio :label='1' :disabled="type === 3">男</Radio>
        <Radio :label='2' :disabled="type === 3">女</Radio>
      </RadioGroup>
    </FormItem>
    <FormItem label="所属单位">
      <Select v-model="formValidate.orgIdList" multiple v-show="type !== 3">
        <Option v-for="item in unitList" :value="item.id" :key="item.id">{{ item.orgName }}</Option>
      </Select>
       <span v-show="type === 3">
         {{ currOrgStr }}
       </span>
    </FormItem>
    <FormItem label="所属部门">
      <Select v-model="formValidate.deptIdList" multiple v-show="type !== 3">
        <Option v-for="item in deptList" :value="item.id" :key="item.id">{{ item.deptName }}</Option>
      </Select>
       <span v-show="type === 3">
         {{ currDeptStr }}
       </span>
    </FormItem>
    <FormItem label="职位" prop="position">
      <Select v-model="formValidate.fkPositionDictId" clearable v-show="type !== 3">
        <Option v-for="item in positionList" :value="item.id" :key="item.id">{{ item.itemName }}</Option>
      </Select>
      <span v-show="type === 3">{{itemName}}</span>
    </FormItem>
    <FormItem label="入职时间" prop="workingDate">
      <DatePicker
      v-show="type !== 3"
       type="date" v-model="formValidate.workingDate" placeholder="入职时间" transfer
                  format="yyyy-MM-dd"></DatePicker>
      <span v-show="type === 3">{{dateFormat}}</span>
    </FormItem>
    <FormItem label="所属角色">
      <Select v-model="formValidate.roleIdList" multiple v-show="type !== 3">
        <Option v-for="item in roleList" :value="item.id" :key="item.id">{{
          item.roleName }}
        </Option>
      </Select>
      <span v-show="type === 3">
         {{ currRoleStr }}
       </span>
    </FormItem>

    <FormItem label="备注">
      <i-input type="textarea" v-model="formValidate.memo" placeholder="" v-show="type !== 3"></i-input>
      <span v-show="type === 3">{{formValidate.memo}}</span>
    </FormItem>
    <FormItem prop="memo" label="创建人" v-show="type === 3">
       <span>{{formValidateView.createUserName}}</span>
    </FormItem>
    <FormItem prop="memo" label="创建时间" v-show="type === 3">
       <span>{{formValidateView.gmtCreate}}</span>
    </FormItem>
    <FormItem prop="memo" label="修改人" v-show="type === 3">
       <span>{{formValidateView.updateUserName}}</span>
    </FormItem>
    <FormItem prop="memo" label="修改时间" v-show="type === 3">
       <span>{{formValidateView.gmtModified}}</span>
    </FormItem>
    <FormItem>
      <Button
        type="primary"
        v-if="type !== 3"
        @click="handleSubmit('formValidate')"
      >确定
      </Button>
      <Button @click="handleReset('formValidate')" style="margin-left: 8px">取消</Button>
    </FormItem>
  </Form>
</template>

<script>
import { isIdCard, passwordComplexityGeneral, isPhone, isAccount, isEmail } from '../../../utils/verification'
import { dateFormat } from '../../../utils/date'
import message from '../../../utils/message'
import { createUser, getUserById, updateUser } from '../../../api/modules/user/user'
import { getDeptSelect } from '../../../api/modules/user/dept'
import { getDictionaryInfoByRootCode } from '../../../api/modules/system/dictionary'

export default {
  name: 'UserManageUpdate',
  props: {
    roleList: {
      type: Array,
      default: () => {
        return []
      }
    },
    unitList: {
      type: Array,
      default: () => {
        return []
      }
    },
    type: {
      type: Number,
      default: 1
    },
    moduleId: {
      type: [String, Number],
      default: ''
    }
  },
  data () {
    return {
      // 表单数据(对象中直接嵌套对象请求时会被转换成formdate格式，因此我们对电话等进行如下绑定)
      formValidate: {
        id: '',
        userAccount: '',
        userName: '',
        userPassword: '',
        memo: '',
        phone: '',
        workNumber: '',
        sex: 0,
        email: '',
        fkPositionDictId: '',
        idCard: '',
        workingDate: '',
        orgIdList: [],
        deptIdList: [],
        roleIdList: []
      },
      deptList: [],
      positionList: [],
      // 表单校验规则
      ruleValidate: {
        userAccount: [{ required: true, message: '当前项不能为空', trigger: 'blur' }, {
          validator: (rule, value, callback) => {
            if (isIdCard(value) || isAccount(value) || this.formValidate.id !== '') {
              callback()
            } else {
              callback(new Error('账户格式为长度4-15位数字字母的组合或16位身份证号码'))
            }
          },
          trigger: 'blur'
        }],
        userName: [{ required: true, message: '当前项不能为空', trigger: 'blur' }],
        userPassword: [{
          validator: (rule, value, callback) => {
            if (passwordComplexityGeneral(value) || value === '') {
              callback()
            } else {
              callback(new Error('您的密码复杂度太低（密码中必须包含字母、数字，长度[6-20]）'))
            }
          },
          trigger: 'blur'
        }],
        phone: [{
          validator: (rule, value, callback) => {
            if (value === '' || isPhone(value)) {
              callback()
            } else {
              callback(new Error('手机号格式错误'))
            }
          },
          trigger: 'blur'
        }],
        idCard: [{
          validator: (rule, value, callback) => {
            if (isIdCard(value) || value === '') {
              callback()
            } else {
              callback(new Error('账户格式为16位身份证号码'))
            }
          },
          trigger: 'blur'
        }],
        email: [{
          validator: (rule, value, callback) => {
            if (isEmail(value) || value === '') {
              callback()
            } else {
              callback(new Error('邮箱格式错误'))
            }
          },
          trigger: 'blur'
        }]
      },
      currOrgList: [],
      currRoleList: [],
      currDeptList: [],
      formValidateView: {}
    }
  },
  computed: {
    dateFormat () {
      if (this.formValidate.workingDate) {
        return dateFormat(this.formValidate.workingDate)
      }
      return ''
    },
    itemName () {
      const arr = this.positionList.filter(item => item.id === this.formValidate.fkPositionDictId)
      if (arr.length > 0) {
        return arr[0].itemName
      }
      return ''
    },
    orgName () {
      return this.unitList.filter(item => item.id === this.formValidate.fkPositionDictId)
    },
    currOrgStr () {
      let str = ''
      this.currOrgList.forEach(item => {
        str += item.orgName + ','
      })
      return str.substring(0, str.length - 1)
    },
    currRoleStr () {
      let str = ''
      this.currRoleList.forEach(item => {
        str += item.roleName + ','
      })
      console.log(str.substring(0, str.length - 1))
      return str.substring(0, str.length - 1)
    },
    currDeptStr () {
      let str = ''
      this.currDeptList.forEach(item => {
        str += item.deptName + ','
      })
      return str.substring(0, str.length - 1)
    }
  },
  created () {
    if (this.type !== 1 && this.type !== -1) {
      this.$_init()
    }
    this.getDeptSelect()
    this.getPositionSelect()
  },
  methods: {
    /**
       * 数据提交执行函数
       * @param name
       */
    handleSubmit (name) {
      this.$refs[name].validate((valid) => {
        // 校验通过
        if (valid) {
          this.formValidate.workingDate = this.formValidate.workingDate ? dateFormat(this.formValidate.workingDate, 'yyyy-MM-dd') : ''
          // 判断用户是新增操作还是编辑操作type为1表示新增，2为编辑
          if (this.type === 1) {
            createUser(this.formValidate).then(data => {
              message.message.success(data.message)
              // 关闭对话框并重新请求数据
              this.$emit('closeView', 1)
            })
          } else if (this.type === 2) {
            updateUser(this.formValidate).then(data => {
              message.message.success(data.message)
              // 关闭对话框并重新请求数据
              this.$emit('closeView', 1)
            })
          }
        } else {
          message.message.error('数据格式错误，请检查后重试')
        }
      })
    },
    /**
       * 取消执行函数
       * @param name
       */
    handleReset (name) {
      // 关闭对话框(不清表单也可以，每次打开的表单都是新的)
      this.$emit('closeView')
    },
    /**
       * 初始化
       */
    $_init () {
      // 新增id属性及version属性
      this.formValidate.id = this.moduleId
      this.formValidate.version = null
      // 请求接口
      getUserById(this.moduleId).then(({ data }) => {
        this.formValidateView = data
        if (data.orgList != null) {
          for (const i in data.orgList) {
            this.formValidate.orgIdList.push(data.orgList[i].id)
          }
          this.currOrgList = data.orgList || []
        }
        if (data.deptList != null) {
          for (const i in data.deptList) {
            this.formValidate.deptIdList.push(data.deptList[i].id)
          }
          this.currDeptList = data.deptList || []
        }
        if (data.roleList != null) {
          for (const i in data.roleList) {
            this.formValidate.roleIdList.push(data.roleList[i].id)
          }
          this.currRoleList = data.roleList || []
        }
        if (data.userInfo != null) {
          Object.keys(data.userInfo).forEach(key => {
            if (key !== 'id' && this.formValidate[key] != null) {
              this.formValidate[key] = data.userInfo[key]
            }
          })
        }
        Object.keys(this.formValidate).forEach(key => {
          if (data[key] != null) {
            this.formValidate[key] = data[key]
          }
        })
      })
    },
    /**
       * 获取部门下拉框
       * @author Enzo
       * @date 2020-6-19
       */
    getDeptSelect () {
      let orgId = ''
      if (this.formValidate.orgIdList.length > 0) {
        orgId = this.formValidate.orgIdList[0]
      }
      getDeptSelect(orgId).then(res => {
        this.deptList = res.data
      })
    },
    /**
     * 获取职务下拉框
     */
    getPositionSelect () {
      const rootCode = 'position'
      getDictionaryInfoByRootCode(rootCode).then(({ data }) => {
        this.positionList = data
      })
    }
  }
}
</script>

<style scoped>

</style>
